import json
import os
import time

from django.views.decorators.csrf import csrf_exempt
from django.conf import settings

from accounts_sys.models import *
from utils.response_utils import *
from utils.session_utils import *

from portal_sys.models import Claim

from elastic_sys.elastic.elastic_manager import get_entity, entity_exists
from elastic_sys.elastic.entity_definer import get_entity_enum_by_type_name, EntityEnum


@csrf_exempt
def portal_claim(request):
    if request.method != 'POST':
        return method_disallowed_response(request.method, 'POST')

    if not has_login(request):
        return login_status_response()

    user = get_login_user(request)
    if user.user_type != "normal":
        return permission_denied_response(user.user_type, 'normal')

    if user.is_claiming:
        return build_response(errno=2001, msg="你已发出过认领请求且在审核中")

    scholar_id = request.POST.get('scholar_id')
    introduction = request.POST.get('introduction')
    file_data = request.FILES.get('file')
    file_name = file_data.name
    file_content = file_data.read()

    has_claim = Claim.objects.filter(scholar_id=str(scholar_id))

    if has_claim.exists():
        has_claim_one = has_claim[0]
        if has_claim_one.status == "pending":
            return build_response(errno=2002, msg="门户已被认领且正在审核中")
        if has_claim_one.status == "approved":
            return build_response(errno=2002, msg="门户已被认领")

    if entity_exists(EntityEnum.scholar, str(scholar_id)) is False:
        return build_response(errno=3001, msg="学者id不存在")

    if str(file_name).split(".")[-1] not in ["jpg", "jpeg", "png"]:
        return build_response(errno=3003, msg="不是有效图片")

    if introduction is None or len(introduction) < 3 or len(introduction) > 511:
        return build_response(errno=3002, msg="个人介绍长度错误（需非空且长度为3至511字符）")

    # 前端上传的图片名称有问题，我来后端兼容下
    if "/" in file_name:
        file_name = str(file_name).split("/")[-1]

    # 防止文件重复，给文件前面拼了一个时间戳，同时新建一个学者id的文件夹
    scholar_path = os.path.join(settings.MEDIA_ROOT, scholar_id)
    if os.path.exists(scholar_path) is False:
        os.mkdir(scholar_path)

    only_file_name = str(int(time.time())) + file_name
    file_path = os.path.join(scholar_path, only_file_name)

    with open(file_path, 'wb') as file:
        file.write(file_content)

    Claim.objects.create(user_id=user, scholar_id=scholar_id, introduction=introduction, material_path=only_file_name,
                         status="pending")
    user.is_claiming = True
    user.save()

    return build_response(msg="认领请求发出成功")


@csrf_exempt
def portal_current(request):
    if request.method != 'GET':
        return method_disallowed_response(request.method, 'GET')

    if not has_login(request):
        return login_status_response()

    user = User.objects.get(id=get_login_id(request))

    if user.user_type not in ["admin", "normal"]:
        return build_response(errno=1004, msg="当前用户类型不是scholar")

    claim = Claim.objects.get(user_id=user)

    entity_enum = get_entity_enum_by_type_name("scholar")

    try:
        entity = get_entity(entity_enum, str(claim.scholar_id))
        if entity is None:
            return build_response(errno=2001, msg="学者门户信息异常")
    except Exception as e:
        print(e)
        return build_response(errno=2001, msg="学者门户信息异常")

    return build_response(other_info={"scholar": entity}, msg="获取成功")


@csrf_exempt
def portal_modify_information(request):
    if request.method != 'POST':
        return method_disallowed_response(request.method, 'POST')

    if not has_login(request):
        return login_status_response()

    user = User.objects.get(id=get_login_id(request))

    data = json.loads(request.body)

    introduction = data.get('introduction')

    has_claim = Claim.objects.filter(user_id=user)
    if not has_claim.exists():
        return build_response(errno=2002, msg="门户不存在")
    has_claim_one = has_claim[0]

    if introduction is None or len(introduction) < 3 or len(introduction) > 511:
        return build_response(errno=3002, msg="个人介绍长度错误（需非空且长度为3至511字符）")

    has_claim_one.introduction = introduction
    has_claim_one.save()

    return build_response(msg="修改成功")


@csrf_exempt
def portal_info_by_id(request, scholar_id):
    if request.method != 'GET':
        return method_disallowed_response(request.method, 'GET')

    claimed_users = User.objects.filter(scholar_id=scholar_id)
    if not claimed_users.exists():
        return build_response(other_info={"claimed": False}, msg="获取成功")
    claimed_user = claimed_users[0]
    return build_response(other_info={"claimed": True, "introduction": claimed_user.introduction}, msg="获取成功")
